import axios from 'axios'
import store from '@/store'
import { getToken } from '@/utils/token'
const requests = axios.create({
  baseURL: 'http://apis.imooc.com/api/',

  timeout: 5000,
  headers: {
    Authorization: 'Bearer ' + getToken() || ''
  }
})

requests.interceptors.request.use(
  (config) => {
    store.commit('SETLOADING', true)
    store.commit('SETERROR', {
      status: false,
      message: ''
    })

    const icode = '9A8DBB1B077B1239'
    config.params = { ...config.params, icode }
    if (config.data instanceof FormData) {
      config.data.append('icode', icode)
    } else {
      config.data = { ...config.data, icode }
    }

    return config
  },
  (err) => {
    console.log(err)
    alert('服务器响应数据失败')
  }
)

requests.interceptors.response.use(
  (res) => {
    setTimeout(() => {
      store.commit('SETLOADING', false)
    }, 200)

    return res.data
  },
  (err) => {
    console.log(err.response.data.error)
    store.commit('SETERROR', {
      status: true,
      message: err.response.data.error
    })
    store.commit('SETLOADING', false)

    alert('服务器响应数据失败' + err)
    return Promise.reject(err.response.data)
  }
)

export default requests
